package cn.ctodb.eadp.uaa.web.rest;

import com.codahale.metrics.annotation.Timed;
import cn.ctodb.eadp.uaa.service.OrgService;
import cn.ctodb.eadp.uaa.web.rest.util.HeaderUtil;
import cn.ctodb.eadp.uaa.web.rest.util.PaginationUtil;
import cn.ctodb.eadp.uaa.service.dto.OrgDTO;
import io.swagger.annotations.ApiParam;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing Org.
 */
@RestController
@RequestMapping("/api")
public class OrgResource {

    private final Logger log = LoggerFactory.getLogger(OrgResource.class);

    private static final String ENTITY_NAME = "org";
        
    private final OrgService orgService;

    public OrgResource(OrgService orgService) {
        this.orgService = orgService;
    }

    /**
     * POST  /orgs : Create a new org.
     *
     * @param orgDTO the orgDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new orgDTO, or with status 400 (Bad Request) if the org has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/orgs")
    @Timed
    public ResponseEntity<OrgDTO> createOrg(@Valid @RequestBody OrgDTO orgDTO) throws URISyntaxException {
        log.debug("REST request to save Org : {}", orgDTO);
        if (orgDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new org cannot already have an ID")).body(null);
        }
        OrgDTO result = orgService.save(orgDTO);
        return ResponseEntity.created(new URI("/api/orgs/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /orgs : Updates an existing org.
     *
     * @param orgDTO the orgDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated orgDTO,
     * or with status 400 (Bad Request) if the orgDTO is not valid,
     * or with status 500 (Internal Server Error) if the orgDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/orgs")
    @Timed
    public ResponseEntity<OrgDTO> updateOrg(@Valid @RequestBody OrgDTO orgDTO) throws URISyntaxException {
        log.debug("REST request to update Org : {}", orgDTO);
        if (orgDTO.getId() == null) {
            return createOrg(orgDTO);
        }
        OrgDTO result = orgService.save(orgDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, orgDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /orgs : get all the orgs.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of orgs in body
     */
    @GetMapping("/orgs")
    @Timed
    public ResponseEntity<List<OrgDTO>> getAllOrgs(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of Orgs");
        Page<OrgDTO> page = orgService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/orgs");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /orgs/:id : get the "id" org.
     *
     * @param id the id of the orgDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the orgDTO, or with status 404 (Not Found)
     */
    @GetMapping("/orgs/{id}")
    @Timed
    public ResponseEntity<OrgDTO> getOrg(@PathVariable Long id) {
        log.debug("REST request to get Org : {}", id);
        OrgDTO orgDTO = orgService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(orgDTO));
    }

    /**
     * DELETE  /orgs/:id : delete the "id" org.
     *
     * @param id the id of the orgDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/orgs/{id}")
    @Timed
    public ResponseEntity<Void> deleteOrg(@PathVariable Long id) {
        log.debug("REST request to delete Org : {}", id);
        orgService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/orgs?query=:query : search for the org corresponding
     * to the query.
     *
     * @param query the query of the org search 
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/orgs")
    @Timed
    public ResponseEntity<List<OrgDTO>> searchOrgs(@RequestParam String query, @ApiParam Pageable pageable) {
        log.debug("REST request to search for a page of Orgs for query {}", query);
        Page<OrgDTO> page = orgService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/orgs");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }


}
